﻿// App
// Application class of FLMScan application
// 
// FLMScan - Featured by FabLab Munich

using System;
using System.Configuration;
using System.Data;
using System.Windows;
using System.IO;
using FLMScan.Tools;
using FLMScan.Parameters;
using FLMScan.Exception;

namespace FLMScan
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static UnhandledExceptionHandler exceptionHandler;

        private App()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // pre-allocate exception handler
            exceptionHandler = UnhandledExceptionHandler.Instance();

            LoggingHelper.MakeLogger();

            string fullExecutablePath = typeof(FLMScanInstance).Assembly.Location;
            string executablePath = Path.GetDirectoryName(fullExecutablePath);

            FLMScanParameters parameters = new FLMScanParameters(executablePath);

            System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo(parameters.UiLanguage);

            if (cultureInfo != null)
                System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;

            MainWindow window = new MainWindow();

            FLMScanViewModel viewModel = (FLMScanViewModel)window.DataContext;
            FLMScanInstance flmScan = FLMScanFactory.Make(FLMScanInstanceType.EProductional, window, viewModel, parameters);

            EventHandler handler = null;
            handler = delegate
            {
                viewModel.OnRequestClose -= handler;
                window.Close();
            };

            viewModel.OnRequestClose += handler;            

            window.Show();                                   
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            exceptionHandler.HandleException(sender, e);
        }
    }
}
